<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言之前所讲的都是通过Koa来实现API操作，或者将数据持久化到数据库中，以上操作都是偏后端的操作。Koa是同时支持前后端操作的框架，下面主要介绍以下三个部分：1、静态资源托管的方式；2、动态模板渲染：使用模板引擎，结合数据库返回的内容，进行动态渲染；3、前后端分离的实践。 静态服务器静态服务器是通过静态HTTP服务器来提供HTML、JS、CSS文件及图片的托管服务的，Node.js世界里的koa">
<meta property="og:type" content="article">
<meta property="og:title" content="前端视图模板">
<meta property="og:url" content="http://example.com/2021/10/24/node/%E5%89%8D%E7%AB%AF%E8%A7%86%E5%9B%BE%E6%A8%A1%E6%9D%BF/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言之前所讲的都是通过Koa来实现API操作，或者将数据持久化到数据库中，以上操作都是偏后端的操作。Koa是同时支持前后端操作的框架，下面主要介绍以下三个部分：1、静态资源托管的方式；2、动态模板渲染：使用模板引擎，结合数据库返回的内容，进行动态渲染；3、前后端分离的实践。 静态服务器静态服务器是通过静态HTTP服务器来提供HTML、JS、CSS文件及图片的托管服务的，Node.js世界里的koa">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-24T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-03T08:19:16.690Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="node狼书">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/10/24/node/%E5%89%8D%E7%AB%AF%E8%A7%86%E5%9B%BE%E6%A8%A1%E6%9D%BF/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>前端视图模板 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/24/node/%E5%89%8D%E7%AB%AF%E8%A7%86%E5%9B%BE%E6%A8%A1%E6%9D%BF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          前端视图模板
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-10-24 12:18:39" itemprop="dateCreated datePublished" datetime="2021-10-24T12:18:39+08:00">2021-10-24</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:19:16" itemprop="dateModified" datetime="2021-11-03T16:19:16+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>之前所讲的都是通过Koa来实现API操作，或者将数据持久化到数据库中，以上操作都是偏后端的操作。Koa是同时支持前后端操作的框架，下面主要介绍以下三个部分：1、静态资源托管的方式；2、动态模板渲染：使用模板引擎，结合数据库返回的内容，进行动态渲染；3、前后端分离的实践。</p>
<h1 id="静态服务器"><a href="#静态服务器" class="headerlink" title="静态服务器"></a>静态服务器</h1><p>静态服务器是通过静态HTTP服务器来提供HTML、JS、CSS文件及图片的托管服务的，Node.js世界里的koa-static、http-server等模块和常见的Apache、Nginx功能类似。</p>
<p>Koa里有一个koa-static模块，是官方提供的静态服务模块，</p>
<h1 id="模板引擎"><a href="#模板引擎" class="headerlink" title="模板引擎"></a>模板引擎</h1><p>前面说得是静态文件处理，但大多数网站是动态得，动态网站需要根据数据变化来进行最终得视图渲染，此时非常适合使用模板引擎。</p>
<p>编译（模板+数据） = HTML。</p>
<p>模板是一种采用复用思想实现得高级写法，其实现原理是：先定义模板，然后再使用的时候将模板和数据一起编译成模板文件。</p>
<p>模板的编译工具称为模板引擎，经典的模板引擎有：EJS、Pug、Nunjucks。</p>
<h1 id="Webpack"><a href="#Webpack" class="headerlink" title="Webpack"></a>Webpack</h1><p>以Node.js为基础的各个模块成为了前端发展各个方面的重要支柱，具体的示例如下：</p>
<p>资源处理：Data URLs；压缩：Uglify、JSMin、Csso；依赖管理：NPM、Bower；图片处理：Imagemin；模块系统：CommonJS、AMD、ES6 Modules；模块加载：RequireJS、JSpm、Sea、PostCSS。</p>
<p>模板引擎：Pug、Handlebars、Nunjucks；JavaScript友好语言：Coffee、Babel、TypeScript；构建：Grunt、Gulp、make；模块打包：Browserify、Webpack。</p>
<p>模块加载器：例如RequireJS，其核心原理是AMD规范，简单易用但缺少线上优化，所以必须依赖Grunt、Gulp等构建工具。  虽然不用管理模块加载，但是要掌握构建工具。而模块打包器则让一切变得简单，Webpack是最流行的模块打包器。</p>
<p>Webpack是一个JS应用程序的静态模块打包器，当Webpack处理应用程序时，它会递归构建一个依赖关系图，其中包含应用程序需要的每一个模块，然后将所有模块打包成一个或多个bundle文件。</p>
<h2 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h2><p>代码分割是Webpack最重要的特性，要点如下：1、在恰当的时机加载需要的模块；2、将第三方库与源码分离；3、实现样式分离；4、实现异步加载分离。</p>
<p>所有的资源都是模块，其中包含如下部分：Entry、Output、Loader、Plugin（包括CommonsChunkPlugin：提取公共模块；DefinePlugin：定义环境变量）、UglifyJsPlugin：实现代码压缩、ExtractTextPlugin：提取样式代码。</p>
<h3 id="css-loader"><a href="#css-loader" class="headerlink" title="css-loader"></a>css-loader</h3><p>在webpack中，可以基于css-loader，在JS文件中通过require的方式引入CSS。具体的实现过程如下：首先需要安装css-loader和style-loader（安装style-loader是为了在HTML中以style的方式嵌入CSS）。</p>
<p>实现要点如下：1、CSS代码被打包到JavaScript中，所有文件都是资源，都可以被打包；2、CSS代码被css-loader处理了；3、Webpack命令会按照配置文件进行编译。</p>
<p>这里很容易理解，首先要根据文件后缀来匹配处理方式。如果是CSS文件，会采用css-loader来处理，如果是less文件，就需要用less-loader来处理，通过less进行预编译的配置如下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">loaders: [</span><br><span class="line">    &#123;</span><br><span class="line">        test: /\.css$/, loader: 'style-loader!css-loader'</span><br><span class="line">    &#125;, </span><br><span class="line">    &#123;</span><br><span class="line">        test: /\.less$/, loader: 'style-loader!css-loader!less-loader'</span><br><span class="line">    &#125;,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h3 id="分割与优化"><a href="#分割与优化" class="headerlink" title="分割与优化"></a>分割与优化</h3><p>webpack-visualizer是Webpack的可视化资源分析工具，在构建Webpack时会自动计算出各个模块在项目工程中的依赖与分布情况，方便我们做出更精确的资源依赖和引用分析；例如：判断项目结构是否合理、依赖引用是否合理。</p>
<p>然而，大多数项目的依赖库体积特别大，内次开发过程中会重新读取和编译对应的依赖资源，且我们很少去修改第三方依赖的源码，为改进上述情况，可以进行以下配置：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在webpack.config.js中增加以下代码，增加vendor选项，并使用webpack.optimize.CommonsChunkPlugin插件</span></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"><span class="keyword">const</span> webpack = <span class="built_in">require</span>(<span class="string">'webpack'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: &#123;</span><br><span class="line">        main: <span class="string">'./src/index.js'</span>,</span><br><span class="line">        vendor: <span class="string">'debug'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: <span class="string">'[chunkhash].[name].js'</span>,</span><br><span class="line">        path: path.resolve(__dirname, <span class="string">'dist'</span>),</span><br><span class="line">    &#125;,</span><br><span class="line">    plugins: [</span><br><span class="line">        <span class="keyword">new</span> webpack.optimize.CommonsChunkPlugin(&#123;</span><br><span class="line">            name: <span class="string">'vendor'</span>,</span><br><span class="line">            minChunks: <span class="literal">Infinity</span></span><br><span class="line">        &#125;)</span><br><span class="line">    ]</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>后面，我们需要在资源中加入external配置项，external可以把依赖资源声明为一个外部依赖，然后通过Script外链脚本引入HTML中。这也是我们早期进行页面开发时引入资源模式的一种翻版。可以告知Webpack，当遇到某类变量名时不用解析和编译至模块的内部文件，改用从外部变量中读取的方法能极大地提升编译速度，同时也能等好地利用CDN来实现缓存。</p>
<p>external的配置相对比较加单，只需要完成以下两步：</p>
<p>1、在页面中加入需要引入的lib地址</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"//cdn.bootcss.com/jquery.min.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"//cdn.bootcss.com/underscore.min.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"/static/common/react.min.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"/static/common/react-dom.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"/static/common/react-router.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"/static/common/immutable.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>2、在webpack.config.js中加入external配置项</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.export = &#123;</span><br><span class="line">    externals: &#123;</span><br><span class="line">        <span class="string">'react-router'</span>: &#123;</span><br><span class="line">            amd: <span class="string">'react-router'</span>,</span><br><span class="line">            root: <span class="string">'ReactRouter'</span>,</span><br><span class="line">            commonjs: <span class="string">'react-router'</span>,</span><br><span class="line">            commonjs2: <span class="string">'react-router'</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">        react: &#123;</span><br><span class="line">            amd: <span class="string">'react'</span>,</span><br><span class="line">            root: <span class="string">'React'</span>，</span><br><span class="line">            commonjs: <span class="string">'react'</span>,</span><br><span class="line">            commonjs2: <span class="string">'react'</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">'react-dom'</span>: &#123;</span><br><span class="line">            amd: <span class="string">'react-dom'</span>,</span><br><span class="line">            root: <span class="string">'ReactDOM'</span>,</span><br><span class="line">            commonjs: <span class="string">'react-dom'</span>,</span><br><span class="line">            commonjs2: <span class="string">'react-dom'</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>配置此类文件前，构建资源包需要采用AMD、CommonJS、CMD进行兼容封装，即打包好得库已经是经过umd模式包装过得库。</p>
<p>优化Webpack构建可以带来很多便利，比如可以利用DllPlugin和DllReferencePlugin预编译资源模块；可以使用HappyPack多进程加速代码构建（生产环境也可以利用多进程加速代码构建）；可以使用webpack-paraller-uglify-plugin提升代码压缩混淆得打包效率。</p>
<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p>Webpack得打包过程如下：1、从配置文件中找到入口；2、解析模块系统；3、解决依赖；4、处理模块依赖（读取、解析、解决）；5、合并所有使用得模块；6、合并模块系统得运行时环境；7、生成打包后得文件。</p>
<p>有了打包后得文件，就可以在浏览器中使用了，在浏览器中加载解析文件得过程如下：</p>
<p>1、通过script标签加载Webpack打包后得文件；2、加载模块运行时环境；3、加载入口文件；4、读取依赖；5、解决依赖；6、执行（带有依赖的）入口文件。</p>
<p>打包构建过程（合并、转换降级、优化、压缩）是由Webpack的Loaders（加载器）和plugins(插件)完成的，开发者只需要关心模块的编写就可以了。</p>
<h2 id="工具化"><a href="#工具化" class="headerlink" title="工具化"></a>工具化</h2><p>实际项目中，如果每个项目都使用Webpack，会导致Webpack配置项很难维护，而且不同项目配置项也不同。我们可以基于webpack设计一个前端开发工具，但配置项统一采用”约定大于配置”的思想，在项目内部尽可能少地进行配置。</p>
<p>YKit是去哪儿网开源的Node.js模块，是对webpack的封装。它用各种插件机制封装了各种类型应用的配置，只需要安装合适的插件就可以把一个基本的开发环境搭配好。Ykit的核心包括三部分：用户编写的模块+Ykit配置项+Ykit插件。</p>
<p>总的来说Ykit只是一个壳，真正的多样化构建依赖于插件，插件是一个个npm模块，它们将构建过程中的配置和功能进行封装，使得Ykit能满足多种多样的需求而不会冲突，并保持了开发的相对一致性。</p>
<p>优化webpack：1、webpack的构建速度慢，很多情况下是每次都还要去一个个寻找文件在资源树中的位置，这里我们在每次找到之后，生成一个hash缓存，下次再寻找时就可以直接按照存储的路径来了。</p>
<p>2、在第一次构建后，如果文件没有变动，就不会出发新的构建操作，因此Ykit只有在第一次启动时略慢，之后启动会很快，且部分改动也只会针对变动文件进行重新构建。</p>
<p>3、另一个webpack中很费时的是压缩资源吗，Ykit采用了多进程的压缩方式，使用Node.js中的cluster弄块实现了多进程并行处理。</p>
<h1 id="前端渲染"><a href="#前端渲染" class="headerlink" title="前端渲染"></a>前端渲染</h1><p>CSR客户端渲染是不需要服务端介入的，但其实从模板时代起就有SSR服务端渲染了。SSR是指采用React、Vue等现代框架，结合Node.js等服务端环境完成页面渲染的一种开发方式。</p>
<p>SSR的目标：1、SEO：搜索引擎优化；2、页面加载性能提升，特别是首屏加载速度；3、架构升级，兼容低版本浏览器。</p>
<p>阿里巴巴开源的Beidou框架：专注于React服务端渲染的同构框架，默认使用src/client目录存放客户端代码，使用src/app目录存放基于Egg.js的服务端代码。</p>
<p>Beidou基于Egg.js生态，具有可插拔的同构能力，其特点如下：</p>
<p>1、beidou-view-react是原有MVC架构中视图层的替代，使用React组件作为视图层模板，可以直接渲染React Component并输出到客户端；</p>
<p>2、beidou-webpack将Webpack集成到了框架中，可在开发阶段提供代码的编译和打包服务；</p>
<p>3、beidou-isomorphic是同构服务器端的React运行时环境；</p>
<p>4、服务器端支持CSS Modules；5、编写纯静态页面时，无须编写任何服务端代码。</p>
<p>Beidou已经简化了React和服务器端之间的组装和优化工作，开发者只需要关注三个点：React组件写法、Webpack配置和Egg.js用法。</p>
<h2 id="React服务端渲染"><a href="#React服务端渲染" class="headerlink" title="React服务端渲染"></a>React服务端渲染</h2><p>在Beidou这样的框架中，同构的意思是：一套代码既可以在服务端运行，又可以在客户端运行，这种同构更像是对语言的统一。</p>
<p>另一个著名的SSR框架是Next.js，它是一个纯粹为SSR应用开发的框架。Next.js式的组件写法如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Page</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span> &#123;props.name&#125; <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Page.getInitialProps = <span class="keyword">async</span>(ctx) =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(&#123;</span><br><span class="line">        name: <span class="string">'Egg + React + SSR'</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Page;</span><br></pre></td></tr></table></figure>

<p>Umi是一个轻量级的、可插拔的企业级React应用框架，它对于antd的集成更友好，在执行umi build命令后，dist目录下会生成umi.server文件，用于服务端渲染。</p>
<p>通过ReactDOMServer的renderToNodeStream分发，umi.server.js将被解析成Stream，然后通过ctx.body完成SSR。Umi SSR的特点如下：1、与框架无关，可以和任何Node.js Web框架集成，甚至可以集成Node.js自带的http模块；2、通过renderToNodeStream方法返回Stream，可以更好地基于Stream进行组装渲染。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/10/24/node/%E5%89%8D%E7%AB%AF%E8%A7%86%E5%9B%BE%E6%A8%A1%E6%9D%BF/" title="前端视图模板">http://example.com/2021/10/24/node/前端视图模板/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/node%E7%8B%BC%E4%B9%A6/" rel="tag"># node狼书</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/22/node/Koa%E7%BB%83%E4%B9%A0/" rel="prev" title="Koa练习">
      <i class="fa fa-chevron-left"></i> Koa练习
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/10/28/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/JavaScript%E7%9A%84%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%88%E4%B8%80%EF%BC%89/" rel="next" title="JavaScript的设计模式（一）">
      JavaScript的设计模式（一） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#静态服务器"><span class="nav-number">2.</span> <span class="nav-text">静态服务器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#模板引擎"><span class="nav-number">3.</span> <span class="nav-text">模板引擎</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Webpack"><span class="nav-number">4.</span> <span class="nav-text">Webpack</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#特性"><span class="nav-number">4.1.</span> <span class="nav-text">特性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#css-loader"><span class="nav-number">4.1.1.</span> <span class="nav-text">css-loader</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分割与优化"><span class="nav-number">4.1.2.</span> <span class="nav-text">分割与优化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原理"><span class="nav-number">4.2.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#工具化"><span class="nav-number">4.3.</span> <span class="nav-text">工具化</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前端渲染"><span class="nav-number">5.</span> <span class="nav-text">前端渲染</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#React服务端渲染"><span class="nav-number">5.1.</span> <span class="nav-text">React服务端渲染</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

